﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace WebLib.FileUpload
{
    public static class UploadHelper
    {
        private const int MaxFileLength = 2097152;

        public static string UploadIconImage(byte[] data, string fileName)
        {
            var uploader = new FileUploader();
            var saveFileRootPath = ConfigurationManager.AppSettings["FileUploadDomain"];

            var middlePath = string.Format(@"{0}\{1}\{2}", @"File\Icon", DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid());

            var directoryPath = Path.Combine(saveFileRootPath, middlePath);

            var ext = Path.GetExtension(fileName);

            var returnValue = uploader.SaveFileObject(data, directoryPath, fileName, ext, false);

            var removedText = ConfigurationManager.AppSettings["FileUploadDomain"] + @"\";

            returnValue = returnValue.Replace(removedText, "");

            return returnValue;
        }

        public static string UploadImageFile(byte[] data, string fileName, bool isUniqueName = true)
        {
            var uploader = new FileUploader();
            var saveFileRootPath = ConfigurationManager.AppSettings["FileUploadDomain"];

            var middlePath = string.Format(@"{0}\{1}", @"File\Images", DateTime.Now.ToString("yyyyMMdd"));

            var directoryPath = Path.Combine(saveFileRootPath, middlePath);

            var ext = Path.GetExtension(fileName);

            var returnValue = uploader.SaveFileObject(data, directoryPath, fileName, ext);

            var removedText = ConfigurationManager.AppSettings["FileUploadDomain"] + @"\";

            returnValue = returnValue.Replace(removedText, "");

            return returnValue;
        }

        public static async Task<string> UploadImageFromHttpPostedFile(HttpPostedFileBase httpPostedFile)
        {
            var saveFileRootPath = ConfigurationManager.AppSettings["FileUploadDomain"];
            if (httpPostedFile == null) return null;
            if (httpPostedFile.ContentLength > MaxFileLength) return null;

            var uploder = new FileUploader();
            var returnValue = await uploder.UploadHttpPostedFileObject(httpPostedFile, saveFileRootPath, DateTime.Now.ToString("yyyyMMdd"));

            return returnValue;
        }

        public static string ToImageUrl(this string physicalPath)
        {
            if (string.IsNullOrEmpty(physicalPath)) return string.Empty;

            return string.Format("http://{0}{1}{2}", ConfigurationManager.AppSettings["SiteUrl"], "/uploadimage/", physicalPath.Replace(@"\", "/"));
        }
    }
}
